<?php
$isReloadable = true;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../_inc/funct.cerBil.php');
require_once('../_inc/funct.xbrlBil.php');
require_once('./_inc/funct.genPhpScript.php');
require_once('../../_inc/funct.tabDati.php');

if (reqVar('azione')=='elimina') {
	$msgPag .= delBil();
}
if (reqVar('azione')=='rielabCorr') {
	$msgPag .= rielabXbrl(reqVar('id'));
}
if (reqVar('azione')=='rielabPrec') {
	$msgPag .= rielabXbrl(reqVar('id_bil_prec'));
}
if (reqVar('azione')=='clonaCorr') {
	$msgPag .= clonaBil(reqVar('id'),reqVar('data_rif'));
}
if (reqVar('azione')=='clonaPrec') {
	$msgPag .= clonaBil(reqVar('id_bil_prec'),reqVar('data_rif_prec'));
}
if (reqVar('azione')=='setVeriCorr') {
	$msgPag .= setVeri(reqVar('id'),reqVar('data_rif'));
}
if (reqVar('azione')=='setVeriPrec') {
	$msgPag .= setVeri(reqVar('id_bil_prec'),reqVar('data_rif_prec'));
}
if (reqVar('azione')=='unsetVeriCorr') {
	$msgPag .= unsetVeri(reqVar('id'),reqVar('data_rif'));
}
if (reqVar('azione')=='unsetVeriPrec') {
	$msgPag .= unsetVeri(reqVar('id_bil_prec'),reqVar('data_rif_prec'));
}

$aVar = array();
$aDefDati = array();
$msg = aVarLoadBil(reqvar('id'),$aVar,$aDefDati,'B',(reqVar('annualizza')=='S'));
$dataRif = $aVar['B_DATA_RIF'];
$mesi = $aVar['B_MESI_BIL'];
$statoLavCorr =  $aVar['B_STATO_LAV'];
$nota = $aVar['B_NOTA_BIL'];
$idSetDati = $aVar['B_ID_SET_DATI'];
$fonteBil = $aVar['B_FONTE_BIL'];

$sSql = "SELECT b.id_bil, b.data_rif, b.id_azienda "
	.", b.descr, b.stato_lav "
	." FROM rgl_bilancio b "
	." WHERE b.id_azienda = ".$aVar['B_ID_AZIENDA']." "
	."    AND b.id_set_dati = ".$idSetDati
	." ORDER BY b.data_rif";
$objDB->query($sSql, 'readBil');
$aBilCorr = array();
$aBilPrec = array(''=>'-- seleziona');
while($aRB = $objDB->fetch('readBil')) {
	$aBilCorr[$aRB['id_bil']] = YMD2DMY($aRB['data_rif'])
		." (".$aRB['stato_lav'].") - ".$aRB['descr'];	
	if ($aRB['data_rif'] < $dataRif) {
		$aBilPrec[$aRB['id_bil']] = YMD2DMY($aRB['data_rif'])
			." (".$aRB['stato_lav'].") - ".$aRB['descr'];	
		if (!isset($_REQUEST['id_bil_prec'])) {
			$_REQUEST['id_bil_prec'] = $aRB['id_bil'];
		}
	}
}

$aVarBP = null;
$aDefDatiP = array();
$dataRifPrec = '';
$mesiPrec = 12;
if (reqvar('id_bil_prec') > 0) {
	$aVarBP = array();
	$msg = aVarLoadBil(reqvar('id_bil_prec'),$aVarBP,$aDefDatiP,'B',(reqVar('annualizzaPrec')=='S'));
	$dataRifPrec = $aVarBP['B_DATA_RIF'];
	$mesiPrec = $aVarBP['B_MESI_BIL'];
	$statoLavPrec =  $aVarBP['B_STATO_LAV'];
}

$sCmdL = '';
$sCmdL .= "<a class='cmd1' href='bilCeePdf.php?id=".reqVarAS('id')."&idp=".reqVarAS('id_bil_prec')
	."&xsn=".XSN."' target='_blank'>PDF</a>";
$sCmdL .= "&nbsp;&nbsp;&nbsp;&nbsp;";
if ($aVar['B_FONTE_BIL']=='bdb01') {
	$sCmdL .= "<a class='cmd1' href='cerBilPdf.php?id=".reqVarAS('id')."&idp=".reqVarAS('id_bil_prec')
		."&xsn=".XSN."' target='_blank'>bilancio origine (BDB)</a>";
	$sCmdL .= "&nbsp;&nbsp;&nbsp;&nbsp;";
}
if ($aVar['B_FONTE_BIL']=='xbrl01') {
	$sCmdL .= "<a class='cmd1' href='xbrl01BilPdf.php?id=".reqVarAS('id')."&idp=".reqVarAS('id_bil_prec')
		."&xsn=".XSN."' target='_blank'>bilancio origine (XBRL)</a>";
	$sCmdL .= "&nbsp;&nbsp;&nbsp;";
	$sCmdL .= "<a class='cmd1' href='xbrl01RacCsv.php?id=".reqVarAS('id')."&xsn=".XSN."' target='_blank'>racc. xbrl</a>";
	$sCmdL .= "&nbsp;&nbsp;&nbsp;";
}
$sCmdL .= "<a class='cmd1' href='bilExp.php?id=".reqVarAS('id')."&xsn=".XSN."' target='_blank'>export</a>";
$sCmdL .= "&nbsp;&nbsp;&nbsp;";
$sCmdL .= "<a class='cmd1' href=\"bilImport.php?id=".reqVarAS('id')."&xsn=".XSN."\">import</a>";

$sCmdR = '';
$sCmdR .= "<a class='cmd1' href='bilRicVis.php?id=".reqVarInt('id')."&idp=".reqVarInt('id_bil_prec')
	."&xsn=".XSN."'>bilancio riclassificato</a>";
$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;";
if (reqVarInt('id_bil_prec')>0) {
	$sCmdR .= "<a class='cmd1' href='renFinVis.php?id=".reqVarInt('id')."&idp=".reqVarInt('id_bil_prec')
		."&xsn=".XSN."'>rendiconto finanziario</a>";
	$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;";
	$sCmdR .= "<a class='cmd1' href='indiciVis.php?id=".reqVarInt('id')."&idp=".reqVarInt('id_bil_prec')
		."&xsn=".XSN."'>indici di bilancio</a>";
}
// se bilancio non utilizzato in alcun rating e' eliminabile
$sSql = "SELECT id_rating "
	." FROM rgl_ratbil "
	." WHERE id_bil = ".reqVarInt('id')
	."    OR id_bil_2 = ".reqVarInt('id')
	."    OR id_bil_3 = ".reqVarInt('id');
$objDB->query($sSql, 'readBil');
$aZ = $objDB->fetch('readBil');
if (!$aZ) {	
	$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;";
	$sCmdR .= "<a class='cmd1' href='javascript:confDel();'>elimina</a>";
}
$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;";
$sCmdR .= "<a class='cmd1' href='bilCeeMod.php?id=".reqVarInt('id')."&idp=".reqVarInt('id_bil_prec')
		."&xsn=".XSN."'>modifica</a>";;
$sCmdR .= cmdTorna('torna');

$aOpzTesta['aMenuVar']['bilancio CEE'] 
	['href'] = RGL_URL_ROOT."/app/ratg/cbil/bilCeeVis.php?id=".reqVarInt('id')."&idp=".reqVarInt('id_bil_prec');
if (reqVarInt('id_bil_prec')>0) {
$aOpzTesta['aMenuVar']['bilancio riclassificato']
	['href'] = RGL_URL_ROOT."/app/ratg/cbil/bilRicVis.php?id=".reqVarInt('id')."&idp=".reqVarInt('id_bil_prec');
$aOpzTesta['aMenuVar']['rendiconto finanziario']
	['href'] = RGL_URL_ROOT."/app/ratg/cbil/renFinVis.php?id=".reqVarInt('id')."&idpverificare=".reqVarInt('id_bil_prec');
$aOpzTesta['aMenuVar']['indici']
	['href'] = RGL_URL_ROOT."/app/ratg/cbil/indiciVis.php?id=".reqVarInt('id')."&idp=".reqVarInt('id_bil_prec');
	}
testaHtml('', $msgPag, 'ratg',$aOpzTesta);
?>
<script type="text/javascript">
<!--
function confDel() {
	if (confirm('Confermi eliminazione ?')) {
		submAz('elimina');
	}
}
function submAz(az) {
	document.frm1.azione.value = az;
	document.frm1.submit();
}
//-->
</script>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="left">
			<? echo $sCmdL; ?>
      </td>
      <td class="cmd1" align="right">

			<? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo getHtmlForm('frm1','',array('enctype'=>true));
echo getHtmlHidden('azione','...');
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('data_rif',$dataRif);
echo getHtmlHidden('data_rif_prec',$dataRifPrec);
?>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<?=getHtmlRigaRif();?>
   <tr>
      <td class="tit1" align="center" colspan='20'><b>Azienda</b></td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Cod.fisc.</td>
      <td class="txt1" align="left" colspan='7'><?=$aVar['B_COD_FISC']?></td>
      <td class="lab1" align="left" colspan='3'>Cod CCIAA</td>
      <td class="txt1" align="left" colspan='7'><?=$aVar['B_COD_CCIAA']?></td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Ragione sociale</td>
      <td class="txt1" align="left" colspan='17'>
      	<a class='txt1' href='anagVis.php?id=<?=$aVar['B_ID_AZIENDA']?>&xsn=<?=XSN?>'>
      	<?=$aVar['B_RAG_SOC']?></a></td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Sede</td>
      <td class="txt1" align="left" colspan='17'><?=$aVar['B_SEDE']?></td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Cod.sett.</td>
      <td class="txt1" align="left" colspan='3'><?=$aVar['B_COD_SETT']?></td>
      <td class="txt1" align="left" colspan='14'><?=$aVar['B_DESCR_SETT']?></td>
   </tr>
	<?
$aOptB = array("onChange"=>"submAz('reload');");
$aOptAnn = array("onClick"=>"submAz('reload');");
$aOptVCS = array("onClick"=>"submAz('setVeriCorr');");
$aOptVCN = array("onClick"=>"submAz('unsetVeriCorr');");
$aOptVPS = array("onClick"=>"submAz('setVeriPrec');");
$aOptVPN = array("onClick"=>"submAz('unsetVeriPrec');");
?>
	<tr>
		<td class='lab1' colspan='3' align='left'>Bilancio corrente</td>
		<td class='txt1' align='left' colspan='13'>
			<?
echo getHtmlSelect('id',$aBilCorr,'@REQ',$aOptB);
if ($mesi != 12) {
	echo getHtmlCheckBox('annualizza', 'S','@REQ',$aOptAnn)." annualizza";
}
echo "&nbsp;&nbsp;&nbsp;";
if ($statoLavCorr=='da verificare') {
	echo getHtmlCheckBox('verificaCorr', 'S','N',$aOptVCS)." verificato";
} else {
	echo getHtmlCheckBox('verificaCorr', 'S','S',$aOptVCN)." verificato";
}
			?>
		</td>
		<td class='txt1' align='center' colspan='4'>
<?
echo "<a href='quadBil.php?id=".reqVar('id')."&xsn=".XSN."' class='txt1'>quadratura</a>";
echo "&nbsp;&nbsp;&nbsp;";
echo "<a href=\"javascript:submAz('rielabCorr');\" class='txt1'>rielabora</a>";
echo "&nbsp;&nbsp;&nbsp;";
echo "<a href=\"javascript:submAz('clonaCorr');\" class='txt1'>clona</a>";
?>		
		</td>
	</tr>
	<tr>
		<td class='lab1' colspan='3' align='left'>Bilancio precedente</td>
		<td class='txt1' align='left' colspan='13'>
			<?
echo getHtmlSelect('id_bil_prec',$aBilPrec,'@REQ',$aOptB);
if ($mesiPrec != 12) {
	echo getHtmlCheckBox('annualizzaPrec', 'S','@REQ',$aOptAnn)." annualizza";
}
echo "&nbsp;&nbsp;&nbsp;";
if ($statoLavPrec=='da verificare') {
	echo getHtmlCheckBox('verificaPrec', 'S','N',$aOptVPS)." verificato";
} else {
	echo getHtmlCheckBox('verificaPrec', 'S','S',$aOptVPN)." verificato";
}
			?>
		<td class='txt1' align='center' colspan='4'>
<?
echo "<a href='quadBil.php?id=".reqVar('id_bil_prec')."&xsn=".XSN."' class='txt1'>quadratura</a>";
echo "&nbsp;&nbsp;&nbsp;";
echo "<a href=\"javascript:submAz('rielabPrec');\" class='txt1'>rielabora</a>";
echo "&nbsp;&nbsp;&nbsp;";
echo "<a href=\"javascript:submAz('clonaPrec');\" class='txt1'>clona</a>";
?>		
		</td>
	</tr>
	<tr>
		<td class='tit1'align='center' colspan='20'><b>BILANCIO</b></td>
	<tr>
<?
if (trim($nota)!='') {
?>
	<tr>
		<td class='txt1'align='left' colspan='20'>
			<?=getHtmlViewNote($nota);?>
		</td>
	<tr>
<?
}

$aGeDati = getGerarcDefDati($aDefDati,1);
//dbg_($aGeDati);
//dbg_($aVar);
foreach($aGeDati as $codX => $aX) {
	echoDato($codX,$aX,$aVar,$aVarBP,0);
}
?>
</table>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="left">
			<? echo $sCmdL; ?>
      </td>
      <td class="cmd1" align="right">
			<? echo $sCmdR; ?>
      </td> 
   </tr>
</table>
<?
echo "</form>\n";

codaHtml();
exit();


function echoDato($codX, $aX, &$aVar, &$aVarBP, $liv) {
	global $dataRif, $dataRifPrec, $mesi, $mesiPrec, $objSess, $objDB;
	$aCSez = array(''=>'-- non sezione --');
	$aCSez['spatt'] = 'Stato patrimoniale - Attivo';
	$aCSez['sppas'] = 'Stato patrimoniale - Passivo';
	$aCSez['cecon'] = 'Conto economico';
	$aCSez['altro'] = 'Altri dati';
	$aCSez['calco'] = 'Dati calcolati';
	
	if ($aX['attr']['cod_sez']!='') {
		echo "<tr><td class='txt1'align='center' colspan='12'><b>".$aCSez[$aX['attr']['cod_sez']]."</b></td>\n"
			."</td><td class='txt1' align='center' colspan='3'><i>".YMD2DMY($dataRif)
			.(($mesi!=12)?" ($mesi mesi)":'')."</i></td>\n"
			."</td><td class='txt1' align='center' colspan='3'><i>".YMD2DMY($dataRifPrec)
			.(($mesiPrec!=12)?" ($mesiPrec mesi)":'')."</i></td>\n"
			."</td><td class='txt1' align='center' colspan='2'><i>".(($dataRifPrec=='')?'':'Variaz.%')."</i></td>\n<tr>\n";
	}
	$codV = 'B_'.$codX;
	$numX = '';
	$valX = '';
	switch ($aX['attr']['tipo_valore']) {
		case 'label':
			break;
		case 'euro':
		case 'num':
			$numX = (isset($aVar[$codV])) ? $aVar[$codV] : 0;
			$valX = number_format($numX,2,',','.');
			break;
	}
	$numY = 0;
	$valY = '';
	$diff = '';
	$diffN = 0;
	if ($aVarBP!=null) {
		switch ($aX['attr']['tipo_valore']) {
			case 'label':
				break;
			case 'euro':
			case 'num':
				$numY = (isset($aVarBP[$codV])) ? $aVarBP[$codV] : 0;
				$valY = number_format($numY,2,',','.');
				$diffN = ($numY!=0) ? ($numX-$numY)*100/abs($numY) : 0;
				$diff = ($diffN!=0) ? number_format($diffN,1,',','.').'%' : '';
				break;
		}					
	} 
	$sColor = '';
	if ($aX['attr']['segnala_variaz'] != 0 && abs($diffN) >  $aX['attr']['segnala_variaz']) {
		$sColor = 'color:red;';
	}
	echo "<tr><td class='txt1' colspan='12'>".str_repeat("&nbsp;",$liv*8)
		."<a href='calcDato.php?cd=$codX&bil1=".reqVarInt('id')."&bil2=".reqVarInt('id_bil_prec')
				."&xsn=".XSN."' class='txt1'>$codX</a> - ".$aX['attr']['descr']
				.((isset($aX['attr']['annualizzato']))?' (a)':'')
		."</td><td class='txt1' align='right' colspan='3'>$valX</td>"
		."</td><td class='txt1' align='right' colspan='3'>$valY</td>"
		."</td><td class='txt1' align='right' colspan='2' style='$sColor'>$diff</td><tr>\n";
	foreach($aX['figli'] as $codY => $aY)  {
		echoDato($codY, $aY, $aVar, $aVarBP, $liv+1);
	}
}

function setVeri($id,$dr) {
	global $objSess, $objDB;
	$sSql = "UPDATE rgl_bilancio SET stato_lav = 'verificato' "
			." WHERE id_bil = ".$id;
	$objDB->query($sSql, 'readBil');
	$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = ".$id
		.",data_ora = '".date('Y-m-d H:i:s')."' "
		.",id_utente = ".intval($objSess->idUtente)
		.",descr_operaz = 'set stato \\'verificato\\'' ";
	$objDB->query($sSql, 'readBil');
	return "impostato stato 'verificato' per bilancio del ".YMD2DMY($dr);
}
function unsetVeri($id,$dr) {
	global $objSess, $objDB;
	$sSql = "UPDATE rgl_bilancio SET stato_lav = 'da verificare' "
			." WHERE id_bil = ".$id;
	$objDB->query($sSql, 'readBil');
	$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = ".$id
		.",data_ora = '".date('Y-m-d H:i:s')."' "
		.",id_utente = ".intval($objSess->idUtente)
		.",descr_operaz = 'set stato \\'da verificare\\'' ";
	$objDB->query($sSql, 'readBil');
	return "impostato stato 'da verificare' per bilancio del ".YMD2DMY($dr);
}
function clonaBil($id,$dr) {
	global $objSess, $objDB;
	$sSql = " SELECT * FROM rgl_bilancio WHERE id_bil = ".$id;
	$objDB->query($sSql, 'clonabil');
	$acX = $objDB->fetch('clonabil');
	$sSql = "INSERT INTO rgl_bilancio SET descr = 'clonato il ".date('d/m/y H:i:s')."'";
	foreach($acX as $nX => $vX) {
		if ($nX == 'id_bil' || $nX == 'descr') continue;
		$sSql .= ', '.$nX." = '".addslashes($vX)."'";
	}
	$objDB->query($sSql, 'clonabil');
	$newid = $objDB->lastInsertId('clonabil');
	$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = ".$newid
		.",data_ora = '".date('Y-m-d H:i:s')."' "
		.",id_utente = ".intval($objSess->idUtente)
		.",descr_operaz = 'clonato' ";
	$objDB->query($sSql, 'clonabil');
	return "clonato bilancio del ".YMD2DMY($dr);
}
function delBil() {
	global $objSess, $objDB;
	//if (headers_sent()) {return "HEADER SENT";}
	//return print_r($objSess->history,1)."<br>".urlTorna('bilancio eliminato');
	$sSql = "SELECT id_rating "
		." FROM rgl_ratbil "
		." WHERE id_bil = ".reqVarInt('id')
		."    OR id_bil_2 = ".reqVarInt('id')
		."    OR id_bil_3 = ".reqVarInt('id');
	$objDB->query($sSql, 'readBil');
	$aZ = $objDB->fetch('readBil');
	if ($aZ) {
		return "Bilancio referenziato in rating - eliminazione non eseguita";
	}
	$sSql = "DELETE FROM rgl_bilancio "
		." WHERE id_bil = ".reqVarInt('id');
	$objDB->query($sSql, 'readBil');
	$sSql = "DELETE FROM rgl_bilancio_log "
		." WHERE id_bil = ".reqVarInt('id');
	$objDB->query($sSql, 'readBil');
	backPage('bilancio eliminato');
	return "???";
}

function rielabXbrl($idBil) {
	global $objDB,$objSess;
	$msg = '';
	$sSql = "SELECT b.id_bil, b.data_rif,  b.file_caricato, b.id_set_dati "
		." FROM rgl_bilancio b "
		." WHERE b.id_bil = ".$idBil;
	$objDB->query($sSql, 'avrld');
	$aRec = $objDB->fetch('avrld');
	if (!$aRec) {
		return 'no bil. '.$idBil;
	}
	
	$aInfo = array('anag'=>array(),'dati'=>array());
	
	if ($aRec['file_caricato'] == '') {
		$msg .= "nessun file caricato<br>";
	}
	if ($msg!='') return $msg;
	$sXml = gzunc($aRec['file_caricato']);
	//dbg_($_FILES['file_xbrl']['tmp_name']." - sXml=".htmlentities(substr($sXml,0,20)));
	
	$pos = strpos($sXml,'<?xml ');
	if ($pos===false) {
		return "File non conforme<br>";
	}
	
	$sSql = "SELECT d.* FROM rgl_def_dato d "
		." WHERE d.id_set_dati = ".$aRec['id_set_dati']
		." ORDER BY d.id_set_dati, d.seq, d.cod_dato ";
	//dbg_($sSql);
	$objDB->query($sSql,'selDefDati');
	$aDefDati = array();
	while($acDD=$objDB->fetch('selDefDati')) {
		$aDefDati[$acDD['cod_dato']] = $acDD;
	}
	//genera script php e livello calcolo
	
	genPhpScript($aDefDati);
	
	$sXml = substr($sXml,$pos);
	$aInfo = array();
	$msg .= xbrl01aInfo($aDefDati, $sXml, $aInfo);
	if ($msg!='') return $msg;
	
	if (!isset($aInfo['dati'][$aRec['data_rif']])) {
		return "data rif. incongruente ".print_r($aInfo,1);
	}		
	$aDati = $aInfo['dati'][$aRec['data_rif']];
	$sSql = "UPDATE rgl_bilancio SET str_def_dati = '".asgzcser($aDefDati)."'"
				.",str_dati = '".asgzcser($aDati)."'"
				.",stato_lav = 'da verificare' "
				." WHERE id_bil = ".$idBil;
	$objDB->query($sSql, 'updBil');
	$sSql = "INSERT INTO rgl_bilancio_log SET id_bil = ".$idBil
		.",data_ora = '".date('Y-m-d H:i:s')."' "
		.",id_utente = ".intval($objSess->idUtente)
		.",descr_operaz = 'Ri-elaborato da XBRL' "
		.",str_dati = '".asgzcser($aDati)."'"
		;
	$objDB->query($sSql, 'updBil');
	$msg .= "ri-elaborato bilacio al ".YMD2DMY($aRec['data_rif'])."<br/>\n";
	return $msg;
	exit();
}
	